<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./css/reset.css">
  <link rel="stylesheet" href="./css/courseDetail.css">
  <title>培训管理</title>
</head>
<script>
  function getParam(name) {
    return location.href.match(new RegExp('[?#&]' + name + '=([^?#&]+)', 'i')) ? RegExp.$1 : '';
  }
  var contextPath =  "/obpm/api"
  var magicHtmlPath = '/obpm/html'
  var obpmFilePath = '/obpm'
  var appName = getParam('magicAppName')
  var appId = getParam('appId')
  var course_id = getParam('course_id') //课程id
  var chapter_id = getParam('chapter_id')
  window.customizationMethod = function(params) {
    console.log('成功')
    // params 是个对象 传参就params.aa
    back(params)
  }
  var ajax = function (data) {
    return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (
            (xhr.status >= 200 && xhr.status < 300) ||
            xhr.status === 304
          ) {
            // resolve(xhr.responseText);
            data.success(xhr.responseText);
          } else {
            console.log('111111')
            reject(xhr.status);
          }
        } else {
          // HTTP请求还在继续...
        }
      };
      xhr.open(data.methods, data.url, data.async);
      xhr.setRequestHeader("content-type", "application/json");

      delete data.methods;
      delete data.url;
      xhr.send(JSON.stringify(data.data));
    });
  };
  //学习记录
  function learnRecord(action_name,params) {
    let data = {
      course_id : course_id,
      chapter_id : chapter_id ? chapter_id : course_id,
      action_name: action_name,
    }
    let time = new Date().getTime()
    let record = {
      methods: "post",
      url: `${obpmFilePath}/magic-api/${appName}/add_learning_record?_=${time}`,
      async: true,
      data:data,
      success: function (result) {
        if(!(params && params.flag)) {
          if(action_name == '结束学习') {
            let oparams = {
              id: chapter_id ? chapter_id : course_id,
            }
            top.obpmOAction('doBack',oparams)
          }
        }
      }
    }
    ajax(record); 
  }
  function back(params) {
    learnRecord('结束学习',params)
  }
  //章节点击
  function handelChapter(chapter_id,chapter_name,course_id) {
    let actionContent = magicHtmlPath + '/' + appName + '/courseDetail.html?course_id='
    +course_id + '&magicAppName=' + appName + '&appId='+appId + '&chapter_id=' + chapter_id
    let params = {
      linkType: '07',
      appId: appId,
      active: true,
      actionContent:actionContent,
      name: chapter_name,
      refreshId: course_id,
      id:chapter_id,
      title:'',
      _select: '',
      magicAppName:appName,
    }
    top.obpmOAction('addTab',params) 
  }
  //收藏/取消收藏
  function toCollect(dom,course_id) {
    let text = dom.innerText
    let collection_type = ( text == '收藏' ) ? "1" : '2'
    let data = {
      course_id: course_id,
      collection_type: collection_type
    }
    let collect = {
      methods: "post",
      url: `${obpmFilePath}/magic-api/${appName}/course_collect`,
      async: true,
      data:data,
      success: function (result) {
        if (result) {
          if(JSON.parse(result).errmsg == '已取消收藏') {
            dom.innerText = '收藏'
          }else if(JSON.parse(result).errmsg == '已收藏') {
            dom.innerText = '取消收藏'
          }
        }
      }
    }
    ajax(collect); 
  }
  function assign() {
    let params = {
      appId: appId,
      actionContent:'__O2dZ7qHKDO7YN3phNVP',
      name: '',
      urlParams: '&course_id='+course_id,
      // refreshId: '',
      // id: '',
      // _select: item.taskId,
    }
    top.obpmOAction('open-eject',params) 
  }
  //分享
  function share() {
    let params = {
      appId: appId,
      actionContent:'__m9hKmsnqpzIbXxZmFKw',
      name: '',
      urlParams: '&course_id='+course_id,
      // refreshId: '',
      // id: '',
      // _select: item.taskId,
    }
    top.obpmOAction('open-eject',params)
  }
  function handlePreview(file) {
    let isImg = false;
    let isVideo = false;
    let isIfc = false;
    let isOffice = false
    if(file.name) {
      let name = file.name.split('.')[file.name.split('.').length - 1];
      name = name.toLowerCase();
      if(
        name == 'png' || 
        name == 'jpg' || 
        name  == 'jpeg' || 
        name == 'gif' ) {
        isImg = true;
      }else if(
        name == 'mp3' || 
        name == 'mp4' 
      ) {
        isVideo = true;
      }else if(
        name == 'ifc'
      ) {
        isIfc = true;
      }
    }
    if(isVideo) {
      let url = window.location.origin + obpmFilePath + file.path
      window.open(url)
      return
    }
    if(isImg) {
      let imgPreview = document.getElementById('imgPreview')
      imgPreview.src = file.url
      document.getElementsByClassName('picture-preview-wrap')[0].style.display = ''
      return
    }
    let realName = file.path.split("/")[file.path.split("/").length - 1];
    let getHasPdfFile = {
      methods: "get",
      url: `${contextPath}/runtime/files/hasPdf?path=${file.path}&fileRealName=${realName}`,
      async: true,
      success: function (result) {
        if (result) {
          if(JSON.parse(result).data){
            toGetenvironment(file,false)
          }
        }
      }
    }
    ajax(getHasPdfFile); 
  }
  function closePreview() {
    document.getElementsByClassName('picture-preview-wrap')[0].style.display = 'none'
  }
  function toGetenvironment(file,onlineEdit) {
    let getenvironment = {
      methods: "get",
      url: `${contextPath}/runtime/files/preview/environment`,
      async: true,
      success: function (result) {
        if (result) {
          if(JSON.parse(result).data=== true) {
            let realName = file.path.split("/")[file.path.split("/").length - 1];
            let pdfPath = '/static'
            let curEditUserId = top.trunkVariable.user.id
            let userName = top.trunkVariable.user.name
            let selectEditPlug = 'tray'
            let showTrackRevisions = true
            let url = pdfPath + '/portal/vue/pdf/pdfviewer.html?action=' + 'false' + 
                "&path=" + file.path + 
                "&name=" + realName + 
                "&showName=" + file.name + 
                "&waterMark=" + null + 
                "&openWaterMark=" + false +
                "&curEditUserId=" + curEditUserId  +
                "&userName=" + userName + 
                "&showTrackRevisions=" + showTrackRevisions +
                "&selectEditPlug=" + selectEditPlug;
                let URL = encodeURI(url)
                window.open(URL);
          }
        }
      }
    }
    ajax(getenvironment); 
  }
  function handelLink(exam_link) {
    window.open(exam_link)
  }
  function togetCourseDetail() {
    let data = {
      course_id:chapter_id ? chapter_id : course_id
    }
    let courseDetail = {
      methods: "post",
      url: `${obpmFilePath}/magic-api/${appName}/course_details`,
      async: true,
      data:data,
      success: function (result) {
        if (result) {
          if(JSON.parse(result)) {
            let course_detail_datas = JSON.parse(result).datas
            let exam_info = course_detail_datas.exam_info
            let exam_link 
            if(exam_info) {
              exam_link = true
            }
            let detailHtml = ''
            let title = document.getElementsByClassName('title')[0] //课程名字
            if(exam_link) {
              title.innerHTML = `
              <span class="topic">${course_detail_datas.course_name}</span>
              <span class="collectBtn" onclick="toCollect(this,'${course_detail_datas.course_id}')">${course_detail_datas.favorite_status == '01' ? '取消收藏': '收藏'}</span>
              <span style="position: absolute;right: 0;cursor: pointer;" onclick="handelLink('${exam_info.exam_link}')">已学习点击去考试</span>
              `
            }else {
              title.innerHTML = `
              <span class="topic">${course_detail_datas.course_name}</span>
              <span class="collectBtn" onclick="toCollect(this,'${course_detail_datas.course_id}')">${course_detail_datas.favorite_status == '01' ? '取消收藏': '收藏'}</span>
              `
            }
            let courseType = document.getElementsByClassName('courseType')[0] //类型
            courseType.innerHTML = `
            <div>
              <span class="type">类型：${course_detail_datas.course_type}</span>
              <span>类目：${course_detail_datas.course_category}</span>
            </div>
            <div>
              ${course_detail_datas.course_founder.name}  ${course_detail_datas.course_created}
            </div>
            `
            let introduce = document.getElementsByClassName('introduce')[0]//简介
            introduce.innerHTML = `
            <span class="desc">简介：</span>
            <div class="flexRight">${course_detail_datas.course_introduction}</div>
            `
            let directory = document.getElementsByClassName('directory')[0]//目录
            let chapter_list = course_detail_datas.chapter_list
            let chapterHtml = ''
            if(chapter_list) {
              for(let i = 0; i <  chapter_list.length; i ++) {
                chapterHtml += `
                  <li class="el-timeline-item" onclick="handelChapter('${chapter_list[i].chapter_id}','${chapter_list[i].chapter_name}','${course_detail_datas.course_id}')">
                    <div class="el-timeline-item__tail"></div>
                    <div class="el-timeline-item__node ${chapter_list[i].learning_status == '01' ? 'el-timeline-item__node_select' : ''}"></div>
                    <div class="el-timeline-item__wrapper">
                      <span class="chapter">第${chapter_list[i].chapter}节：${chapter_list[i].chapter_name}</span>
                      <span class="complete">${chapter_list[i].learning_status == '01' ? '（已完成）' : ''}</span>
                    </div>
                  </li>
                `
              }
              directory.innerHTML = `
                <span class="desc">目录：</span>
                <div class="flexRight">
                  <ul class="el-timeline">
                    ${chapterHtml}
                  </ul>
                </div>
              `
            }
            let attachment = document.getElementsByClassName('attachment')[0]//附件
            let course_annex = course_detail_datas.course_annex
            if(course_annex) {
              course_annex = JSON.parse(course_annex)
              attachment.innerHTML = `
              <span class="desc">附件：</span>
              <div class="flexRight"></div> 
              `
              let flexRight = attachment.children[1]
              let flexRightHtml = ''
              course_annex.forEach(item => {
                flexRightHtml +=  `
                  <div class="fileBox" onclick="handlePreview(${JSON.stringify(item).replace(/"/g, '&quot;')})">${item.showName ? item.showName : item.name}</div>
                `
              })
              flexRight.innerHTML = flexRightHtml
            }
            let article = document.getElementsByClassName('article')[0]//文章 
            article.innerHTML = `
            <span class="desc">文章：</span>
            <div class="flexRight">${course_detail_datas.course_article}</div>
            `
            let video = document.getElementsByClassName('video')[0]//视频
            let file = document.getElementsByClassName('file')[0]//文档
            let course_file = course_detail_datas.course_file
            if(course_detail_datas.course_type != '视频' && course_file) {
              course_file = JSON.parse(course_file)
              file.innerHTML = `
              <span class="desc">文档：</span>
              <div class="flexRight"></div> 
              `
              let flexRight = file.children[1]
              let flexRightHtml = ''
              course_file.forEach(item => {
                flexRightHtml +=  `
                  <div class="fileBox" onclick="handlePreview(${JSON.stringify(item).replace(/"/g, '&quot;')})">${item.showName ? item.showName : item.name}</div>
                `
              })
              flexRight.innerHTML = flexRightHtml
            }
            if(course_detail_datas.course_type == '视频') {
              course_file = JSON.parse(course_file)
              video.innerHTML = `
              <span class="desc">视频：</span>
              <div class="flexRight"></div>
              `
              let flexRight = video.children[1]
              let flexRightHtml = ''
              let width = document.body.clientWidth - 140
              course_file.forEach(item => {
                flexRightHtml +=  `
                  <div class="fileBox">
                    <video width="${width}" height="400" controls autoplay>
                      <source src="${course_file[0].url}" type="video/mp4">
                    </video>
                  </div>
                `
              })
              flexRight.innerHTML = flexRightHtml
              article.style.display = 'none'
              directory.style.display = 'none'
              file.style.display = 'none'
              attachment.style.display = 'none'
            }
            if(course_detail_datas.course_type == '系列课') {
              article.style.display = 'none'
              video.style.display = 'none'
              file.style.display = 'none'
            }else if(course_detail_datas.course_type == '文档') {
              article.style.display = 'none'
              video.style.display = 'none'
              directory.style.display = 'none'
            }else if(course_detail_datas.course_type == '文章') {
              video.style.display = 'none'
              directory.style.display = 'none'
              file.style.display = 'none'
            }
            if(course_detail_datas.course_type != '系列课') {
              learnRecord('开始学习')
            }
          }else {
          }
        }
      },
    };
    ajax(courseDetail); 
  }
</script>
<body onload="togetCourseDetail()">
  <div id="main">
    <div class="header">
      <span class="btn" onclick="back()">返回</span>
      <span class="btn" onclick="share()">分享</span>
      <span class="btn" onclick="assign()">指派</span>
    </div>
    <div class="content">
      <div class="title" style="position: relative;"></div>
      <div class="courseType"></div>
      <div class="introduce"></div>
      <div class="article"></div>
      <div class="video">
        <!-- <span class="desc">视频：</span>
        <div class="flexRight">
          <div class="fileBox">
            <video width="320" height="240" controls autoplay>
              <source src="./img/abc.mp4" type="video/mp4">
            </video>
          </div>
        </div> -->
      </div>
      <div class="directory"></div>
      <div class="file"></div>
      <div class="attachment"></div>
    </div>
    <div class="picture-preview-wrap" style="display: none;" id="picture-preview-wrap">
      <div class="picture-list">
        <div class="img-box">
          <img  class="img" src="" id="imgPreview">
        </div>
      </div>
      <div class="icon-dlose" onclick="closePreview()"> x </div>
    </div>
  </div>
</body>
</html>